package com.hmdp.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.service.IUserInfoService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        //  发送短信验证码并保存验证码
        // 使用正则表达式判断手机号格式
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式不正确");
        }
        String code = RandomUtil.randomString(6);
        // redis 存储验证码
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, code, 5, TimeUnit.MINUTES);
//        session.setAttribute("code", code);
        log.debug("发送短信验证码成功，验证码为：{}", code);
        return Result.ok();
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        // 实现登录功能
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式不正确");
        }
        // 从redis中获取验证码
        Object codeVal = redisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
//        Object codeVal = session.getAttribute("code");
        String code = loginForm.getCode();
        if (code == null || codeVal == null || !code.equals(codeVal.toString())){
            return Result.fail("验证码错误");
        }

        User user = userService.lambdaQuery()
                .eq(phone != null, User::getPhone, phone)
                .one();
        if (user == null){
            user = createNewUser(phone);
        }
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        UUID token = UUID.randomUUID();
        redisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY + token,
                BeanUtil.beanToMap(BeanUtil.copyProperties(user, UserDTO.class)));
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        return Result.ok(token);
    }

    private User createNewUser(String phone) {
        User user = new User();
        user.setCreateTime(LocalDateTime.now());
        user.setPhone(phone);
        user.setNickName("HMDP_" + RandomUtil.randomNumbers(6));
        userService.save(user);
        return user;
    }

    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        // 用户退出的话 清理用户的redis token

        String token = request.getHeader("authorization");
        System.out.println(token);
        if (token == null){
            // 清除redis中的token
            redisTemplate.opsForHash()
                    .delete(RedisConstants.LOGIN_USER_KEY + token);
        }

        return Result.ok("退出登录成功");
    }

    @GetMapping("/me")
    public Result me(){
        // 获取当前登录的用户并返回
        return Result.ok(UserHolder.getUser());
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }

    @GetMapping("/{id}")
    public Result queryUserById(@PathVariable("id") Long id){
        return userService.queryUserById(id);
    }
}
